/*
 *  Copyright (c) 2022 ZhuHai Jieli Technology Co.,Ltd.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#ifndef _PRINTF_C_
#define _PRINTF_C_

#ifdef _DEBUG

AT_RAM static void vm_putbyte(char a)
{
    if (a == '\n') {
        while ((UT2_CON & BIT(15)) == 0);
        UT2_BUF = '\r';
        __asm_csync();
    }
    while ((UT2_CON & BIT(15)) == 0);    // TX IDLE
    UT2_BUF = a;
    __asm_csync();
}

AT_RAM static void vm_putchar(char a)
{
    if (a == '\n') {
        vm_putbyte(0x0d);
        vm_putbyte(0x0a);
    } else {
        vm_putbyte(a);
    }
}

AT_RAM static void vm_put_u4hex(u8 dat)
{
    dat = 0xf & dat;
    if (dat > 9) {
        vm_putbyte(dat - 10 + 'A');
    } else {
        vm_putbyte(dat + '0');
    }
}

AT_RAM static void vm_put_u16hex0(u16 dat)
{
    vm_putbyte('0');
    vm_putbyte('x');

    vm_put_u4hex(dat >> 12);
    vm_put_u4hex(dat >> 8);

    vm_put_u4hex(dat >> 4);
    vm_put_u4hex(dat);
    vm_putchar(' ');
}

AT_RAM static void vm_put_u32hex0(u32 dat)
{
    vm_putbyte('0');
    vm_putbyte('x');
    vm_put_u4hex(dat >> 28);
    vm_put_u4hex(dat >> 24);

    vm_put_u4hex(dat >> 20);
    vm_put_u4hex(dat >> 16);

    vm_put_u4hex(dat >> 12);
    vm_put_u4hex(dat >> 8);

    vm_put_u4hex(dat >> 4);
    vm_put_u4hex(dat);
    vm_putchar(' ');
}

AT_RAM static void vm_put_u8hex0(u8 dat)
{
    vm_putbyte('0');
    vm_putbyte('x');
    vm_put_u4hex(dat >> 4);
    vm_put_u4hex(dat);
    vm_putchar(' ');
}

AT_RAM static void vm_put_buf(u8 *buf, u32 len)
{
    u32 i ;
    for (i = 0 ; i < len ; i++) {
        if ((i % 16) == 0) {
            vm_putbyte('\n') ;
        }
        vm_put_u4hex(buf[i] >> 4);
        vm_put_u4hex(buf[i]);
        vm_putchar(' ');
    }
}

#else

#define vm_putbyte(...)
#define vm_putchar(...)
#define vm_put_u4hex(...)
#define vm_put_u16hex0(...)
#define vm_put_u32hex0(...)
#define vm_put_u8hex0(...)
#define vm_put_buf(...)

#endif

#endif

